Page({
  data: {
    raceTime: '',
    raceTimeDisplay: '',
    raceLocation: '',
    showTimeModal: false,
    years: [],
    months: [],
    days: [],
    datePickerValue: [0, 0, 0],
    startTime: '16:00',
    endTime: '18:00',
    signupList: Array(28).fill(null),
    signupCount: 0,
    showSignupAction: false,
    signupIndex: -1,
    showMatchModal: false,
    girlSetting: 'standard',
    matchCount: 9,
    matchList: [],
    disclaimerChecked: true,
    selectedItemIndex: 0,
    scoreModalVisible: false,
    scoreModalIndex: -1,
    scoreLeft: '',
    scoreRight: '',
    scoreModalLeft: [],
    scoreModalRight: [],
    resultList: [],
    userInfo: null,
    courtCount: 1,
    maxCourtCount: 1,
    safePaddingTop: 0,
    showGenderSelect: false,
    tempOtherName: '',
    tempOtherGender: 'male',
    showEditTitleModal: false,
    editTitleValue: '',
    raceTitle: '',
    defaultRaceTitle: '固搭循环赛 | 7-3发布',
    showOtherSignupModal: false,
    finishedCount: 0,
    scoreTabIndex: 0,
    scoreTabList: [
      { title: '全部', count: 0 },
      { title: '未结束', count: 0 },
      { title: '可以比赛', count: 0 },
      { title: '比赛中', count: 0 }
    ],
    filteredMatchList: [],
    showRegenMatchBtn: false,
    maxPlayers: 8,
    appliedCount: 0,
    roundType: 'single', // 比赛循环次数：single-单循环，double-双循环，custom-自定义
    customRoundCount: 3, // 自定义循环次数
    showQuickSignupModal: false,
    quickSignupText: '',
    quickSignupPreviewPages: [],
    quickSignupPreviewPageIndex: 0,
    quickSignupPreviewPageSize: 15,
    editSignupIndex: -1, // 新增：编辑报名时记录索引
    editSignupName: '', // 新增：编辑报名时记录昵称
    editSignupGender: 'male', // 新增：编辑报名时记录性别
    showEditSignupModal: false, // 新增：编辑报名弹窗是否显示
    modalOpen: false, // 防止多次弹窗
    raceInfo: null,
    shareImagePath: '', // 存储生成的分享图路径
    shareTitle: '羽毛球固搭循环赛邀请',
    sharePath: '/pages/fixedRace/fixedRace',
    isCreator: false, // 是否为创建人
    partnerGroups: [], // 搭档组信息
    scoreModalVisible: false, // 计分弹窗是否显示
    currentScoreIndex: -1, // 当前正在计分的比赛索引
    leftScore: '', // 左方比分
    rightScore: '' // 右方比分
  },
  onLoad(options) {
    if (!options.id) {
      wx.showToast({ title: '缺少比赛ID', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }
    this.options = options;
    this.raceId = options.id;
    
    // 引入本地数据管理器
    const localDataManager = require('../../utils/localDataManager.js');
    this.localDataManager = localDataManager;
    
    // 获取系统状态栏和导航栏高度
    wx.getWindowInfo({
      success: res => {
        const statusBarHeight = res.statusBarHeight || 20;
        const navBarHeight = 44; // 可根据实际微调
        this.setData({
          safePaddingTop: statusBarHeight + navBarHeight
        });
      }
    });
    
    // 从本地存储加载比赛基本信息
    const raceId = options.id;
    const raceData = localDataManager.getRace(raceId);
    
    if (raceData) {
      let selectedItemIndex = 0;
      let showRegenMatchBtn = false;
      if (raceData.status === '计分中') {
        selectedItemIndex = 1;
        showRegenMatchBtn = true;
      } else if (raceData.status === '已完赛') {
        selectedItemIndex = 2;
        showRegenMatchBtn = true;
      }
      
      // 判断是否为创建人
      const app = getApp();
      const currentUser = app.globalData.userInfo;
      const isCreator = currentUser && raceData.creator && 
                       (currentUser.userId === raceData.creator.userId || 
                        currentUser.phone === raceData.creator.phone);
      
      // 从raceData中获取maxPlayers值
      let maxPlayers = raceData.maxPlayers;
      // 只有在maxPlayers不存在或为6（旧版本）时才设置默认值
      if (maxPlayers === undefined || maxPlayers === 6) {
        maxPlayers = 8;
        raceData.maxPlayers = maxPlayers;
        this.localDataManager.saveRace(raceData);
      }
      
      this.setData({
        raceTitle: raceData.title || '',
        raceTimeDisplay: raceData.dateStr || '',
        raceLocation: raceData.location || '',
        selectedItemIndex,
        showRegenMatchBtn,
        maxPlayers: maxPlayers,
        courtCount: raceData.courtCount || 1,
        isCreator: isCreator,
        raceInfo: {
          name: raceData.title || '',
          dateStr: raceData.dateStr || '',
          location: raceData.location || '',
          totalNum: maxPlayers
        }
      }, () => {
        this.loadSignupList();
      });
      console.log('比赛信息加载', raceData);
      console.log('是否为创建人:', isCreator);
    } else {
      wx.showToast({ title: '比赛不存在', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
    }
    const date = new Date();
    const years = [];
    for (let i = date.getFullYear(); i <= date.getFullYear() + 2; i++) years.push(i);
    const months = [];
    for (let i = 1; i <= 12; i++) months.push(i);
    const days = this.getDaysInMonth(date.getFullYear(), date.getMonth() + 1);
    const datePickerValue = [0, date.getMonth(), date.getDate() - 1];
    this.setData({ years, months, days, datePickerValue, signupCount: 0 });
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({ userInfo: app.globalData.userInfo });
    }
    this.updateCourtCountLimit();
    this.loadMatchList();
  },
  getDynamicRaceTitle(maxPlayers, dateStr) {
    return `${maxPlayers}人固搭循环赛 | ${dateStr || ''}`;
  },
  getDefaultRaceTitle(dateStr) {
    return `固搭循环赛 | ${dateStr || ''}`;
  },
  getDaysInMonth(year, month) {
    const days = [];
    const dayCount = new Date(year, month, 0).getDate();
    for (let i = 1; i <= dayCount; i++) days.push(i);
    return days;
  },
  // 生成海报
  async generatePoster() {
    try {
      const ctx = wx.createCanvasContext('posterCanvas', this);
      
      // 1. 绘制背景
      ctx.setFillStyle('#ffffff');
      ctx.fillRect(0, 0, 300, 500);
      
      // 2. 绘制内容（添加错误处理）
      //await this.drawImageWithFallback(ctx, '/images/badminton.jpeg', 20, 20, 260, 260);
      
      // 3. 绘制文字
      ctx.setFontSize(18);
      ctx.setFillStyle('#333333');
      ctx.fillText('羽毛球比赛', 30, 300);
      
      // 4. 生成临时文件
      const tempFilePath = await new Promise((resolve, reject) => {
        ctx.draw(false, () => {
          setTimeout(() => {
            wx.canvasToTempFilePath({
              canvasId: 'posterCanvas',
              success: (res) => resolve(res.tempFilePath),
              fail: reject
            }, this);
          }, 300);
        });
      });
      
      this.setData({ tempFilePath, posterReady: true });
      return tempFilePath;
      
    } catch (err) {
      console.error('生成海报失败:', err);
      throw err;
    }
  },

  // 带错误处理的图片绘制
  drawImageWithFallback(ctx, imgPath, x, y, width, height) {
    return new Promise((resolve) => {
      wx.getImageInfo({
        src: imgPath,
        success: (res) => {
          ctx.drawImage(res.path, x, y, width, height);
          resolve();
        },
        fail: (err) => {
          console.error('图片加载失败:', imgPath, err);
          // 绘制默认背景
          ctx.setFillStyle('#f0f0f0');
          ctx.fillRect(x, y, width, height);
          resolve();
        }
      });
    });
  },

  // 点击分享按钮
  async handleShare() {
    if (!this.data.tempFilePath) {
      wx.showLoading({ title: '生成分享图中...' });
      try {
        await this.generatePoster();
      } catch (err) {
        wx.showToast({ title: '生成分享图失败', icon: 'none' });
        wx.hideLoading();
        return;
      }
      wx.hideLoading();
    }
    
  },

  // 分享配置
  onShareAppMessage() {
    const id = this.data.raceId || (this.options && this.options.id) || '';
    return {
      title: this.data.shareTitle,
      path: `/pages/raceEnroll/raceEnroll?id=${id}`
      // 不设置 imageUrl，让微信自动生成页面内容卡片
    };
  },
  // 朋友圈分享
  onShareTimeline() {
    const id = this.data.raceId || (this.options && this.options.id) || '';
    return {
      title: this.data.shareTitle,
      query: `id=${id}&from=timeline`
      // 不设置 imageUrl
    };
  },
  onEditTime() {
    if (!this.data.isCreator) {
      wx.showToast({ title: '只有创建人才能修改', icon: 'none' });
      return;
    }
    this.setData({ showTimeModal: true });
  },
  onCloseTimeModal() {
    this.setData({ showTimeModal: false });
  },
  onDateChange(e) {
    const { years, months } = this.data;
    const [yearIdx, monthIdx, dayIdx] = e.detail.value;
    const year = years[yearIdx];
    const month = months[monthIdx];
    const days = this.getDaysInMonth(year, month);
    let newDayIdx = dayIdx;
    if (dayIdx >= days.length) newDayIdx = days.length - 1;
    this.setData({
      datePickerValue: [yearIdx, monthIdx, newDayIdx],
      days
    });
  },
  onStartTimeChange(e) {
    this.setData({ startTime: e.detail.value });
  },
  onEndTimeChange(e) {
    this.setData({ endTime: e.detail.value });
  },
  onConfirmTime() {
    const { years, months, days, datePickerValue, startTime, endTime } = this.data;
    const year = years[datePickerValue[0]];
    const month = months[datePickerValue[1]];
    const day = days[datePickerValue[2]];
    const dateStr = `${year}-${month < 10 ? '0'+month : month}-${day < 10 ? '0'+day : day}`;
    const display = `${dateStr} ${startTime} 至 ${endTime}`;
    const raceId = this.options && this.options.id;

    // 更新本地存储中的比赛信息
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) {
      raceData.dateStr = display;
      this.localDataManager.saveRace(raceData);
      
      wx.showToast({ title: '时间已更新' });
      this.setData({
        raceTime: `${dateStr} ${startTime}-${endTime}`,
        raceTimeDisplay: display,
        showTimeModal: false
      });
    } else {
      wx.showToast({ title: '比赛不存在', icon: 'none' });
    }
  },
  onEditLocation() {
    if (!this.data.isCreator) {
      wx.showToast({ title: '只有创建人才能修改', icon: 'none' });
      return;
    }
    
    wx.showModal({
      title: '编辑比赛地点',
      content: this.data.raceLocation || '',
      placeholderText: '请输入比赛地点',
      editable: true,
      success: (res) => {
        if (res.confirm && res.content) {
          const newLocation = res.content.trim();
          if (newLocation) {
            this.setData({
              raceLocation: newLocation
            });
            
            // 更新比赛信息
            const raceData = this.localDataManager.getRace(this.raceId);
            if (raceData) {
              raceData.location = newLocation;
              this.localDataManager.saveRace(raceData);
            }
            
            wx.showToast({ title: '地点修改成功', icon: 'success' });
          }
        }
      }
    });
  },
  // ======= 登录授权统一处理 =======
  ensureLogin(callback) {
    let userInfo = this.data.userInfo || getApp().globalData.userInfo;
    if (userInfo) {
      if (typeof callback === 'function') callback();
      return;
    }
    wx.showModal({
      title: '温馨提示',
      content: '你还未登录，请登录后再进行操作',
      confirmText: '登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.getUserProfile({
            desc: '用于完善会员资料',
            success: res => {
              getApp().globalData.userInfo = res.userInfo;
              this.setData({ userInfo: res.userInfo });
              wx.showToast({ title: '登录成功', icon: 'success' });
              if (typeof callback === 'function') callback();
            },
            fail: err => {
              wx.showToast({ title: '微信授权失败', icon: 'none' });
            }
          });
        }
        // 取消时什么都不做
      }
    });
  },
  onSignupTap(e) {
    const index = e.currentTarget.dataset.index;
    const { signupList } = this.data;
    this.ensureLogin(() => {
      let currentUser = this.data.userInfo || getApp().globalData.userInfo;
      const item = signupList[index];
      
      // 检查当前用户是否已经报名
      const signupDataList = this.localDataManager.getSignups(this.raceId);
      const hasSigned = signupDataList && signupDataList.some(signup => 
        signup.userInfo && signup.userInfo.nickName === currentUser.nickName
      );
      
      if (!item || !item.nickName || !item._id) {
        // 空位：显示报名选项，如果用户已报名则隐藏"本人报名"选项
        this.setData({ showSignupAction: true, signupIndex: index, hasSigned: hasSigned });
        return;
      }
      
      // 检查是否是当前用户的报名
      const isCurrentUserSignup = item.nickName === currentUser.nickName;
      
      if (isCurrentUserSignup) {
        // 当前用户的报名：显示编辑/取消选项
        wx.showActionSheet({
          itemList: ['编辑', '取消报名'],
          success: (res) => {
            if (res.tapIndex === 0) {
              this.setData({
                editSignupIndex: index,
                editSignupName: item.nickName,
                editSignupGender: item.gender || 'male',
                showEditSignupModal: true
              });
            } else if (res.tapIndex === 1) {
              wx.showModal({
                title: '取消报名',
                content: '确定要取消该报名吗？',
                confirmText: '取消报名',
                cancelText: '关闭',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    const raceId = this.options && this.options.id;
                    
                    // 从本地存储中删除报名
                    this.localDataManager.removeSignup(raceId, item._id);
                    wx.showToast({ title: '已取消报名' });
                    
                    // 更新比赛信息
                    const raceData = this.localDataManager.getRace(raceId);
                    if (raceData) {
                      raceData.courtCount = this.data.courtCount;
                      this.localDataManager.saveRace(raceData);
                    }
                    
                    this.loadSignupList();
                  }
                }
              });
            }
          }
        });
      } else {
        // 其他人的报名：允许编辑（移除限制）
        wx.showActionSheet({
          itemList: ['编辑', '取消报名'],
          success: (res) => {
            if (res.tapIndex === 0) {
              this.setData({
                editSignupIndex: index,
                editSignupName: item.nickName,
                editSignupGender: item.gender || 'male',
                showEditSignupModal: true
              });
            } else if (res.tapIndex === 1) {
              wx.showModal({
                title: '取消报名',
                content: '确定要取消该报名吗？',
                confirmText: '取消报名',
                cancelText: '关闭',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    const raceId = this.options && this.options.id;
                    
                    // 从本地存储中删除报名
                    this.localDataManager.removeSignup(raceId, item._id);
                    wx.showToast({ title: '已取消报名' });
                    
                    // 更新比赛信息
                    const raceData = this.localDataManager.getRace(raceId);
                    if (raceData) {
                      raceData.courtCount = this.data.courtCount;
                      this.localDataManager.saveRace(raceData);
                    }
                    
                    this.loadSignupList();
                  }
                }
              });
            }
          }
        });
      }
    });
  },
  onCloseSignupAction() {
    this.setData({ showSignupAction: false, signupIndex: -1 });
  },
  updateSignupCount() {
    const count = this.data.signupList.filter(item => item).length;
    this.setData({ signupCount: count });
    this.updateCourtCountLimit();
  },
  onSignupSelf() {
    this.ensureLogin(() => {
      let userInfo = this.data.userInfo || getApp().globalData.userInfo;
      const { signupIndex } = this.data;
      const raceId = this.options && this.options.id;
      
      // 检查用户是否已经报名
      const signupDataList = this.localDataManager.getSignups(raceId);
      const hasSigned = signupDataList && signupDataList.some(signup => 
        signup.userInfo && signup.userInfo.nickName === userInfo.nickName
      );
      
      if (hasSigned) {
        wx.showToast({ 
          title: '您已报名，不能重复报名', 
          icon: 'none',
          duration: 2000
        });
        this.setData({ showSignupAction: false, signupIndex: -1 });
        return;
      }
      
      // 兼容微信用户信息的 gender 字段（1男2女0未知）和字符串格式
      let gender = 'male';
      if (userInfo.gender === 2 || userInfo.gender === 'female') {
        gender = 'female';
      } else if (userInfo.gender === 1 || userInfo.gender === 'male') {
        gender = 'male';
      } else {
        // 如果性别未知，默认为男性
        gender = 'male';
      }
      
      // 根据性别设置头像
      let avatarUrl = userInfo.avatarUrl;
      if (gender === 'female') {
        avatarUrl = '../../images/avatar_girl.png';
      } else if (gender === 'male') {
        avatarUrl = '../../images/avatar_boy.png';
      }
      
      // Use the clicked position as order, maintaining position
      const order = signupIndex;
      
      // 添加到本地存储
      const signupData = {
        raceId,
        order: order,
        userInfo: {
          nickName: userInfo.nickName,
          avatarUrl: avatarUrl,
          gender: gender
        }
      };
      
      const success = this.localDataManager.addSignup(raceId, signupData);
      if (success) {
        wx.showToast({ title: '报名成功', icon: 'success' });
        
        // 更新比赛信息
        const raceData = this.localDataManager.getRace(raceId);
        if (raceData) {
          raceData.courtCount = this.data.courtCount;
          this.localDataManager.saveRace(raceData);
        }
        
        this.setData({ showSignupAction: false, signupIndex: -1 }, () => {
          this.loadSignupList();
        });
      } else {
        wx.showToast({ title: '报名失败', icon: 'none' });
      }
    });
  },
  onSignupOther() {
    this.setData({
      showOtherSignupModal: true,
      tempOtherName: '',
      tempOtherGender: 'male'
    });
  },
  onOtherNameInput(e) {
    this.setData({
      tempOtherName: e.detail.value
    });
  },
  onSelectGender(e) {
    this.setData({
      tempOtherGender: e.currentTarget.dataset.gender
    });
  },
  onConfirmOtherSignup() {
    const { signupIndex, tempOtherName, tempOtherGender } = this.data;
    if (!tempOtherName.trim()) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    const raceId = this.options && this.options.id;
    
    // 检查是否已经存在相同姓名的报名
    const signupDataList = this.localDataManager.getSignups(raceId);
    const hasSigned = signupDataList && signupDataList.some(signup => 
      signup.userInfo && signup.userInfo.nickName === tempOtherName
    );
    
    if (hasSigned) {
      wx.showToast({ 
        title: '该选手已报名，不能重复报名', 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    let avatarUrl = '../../images/avatar_boy.png';
    if (tempOtherGender === 'female') {
      avatarUrl = '../../images/avatar_girl.png';
    }
    
    // Use the clicked position as order, maintaining position
    const order = signupIndex;
    
    // 添加到本地存储
    const signupData = {
      raceId,
      order: order,
      userInfo: {
        nickName: tempOtherName,
        avatarUrl: avatarUrl,
        gender: tempOtherGender
      }
    };
    
    const success = this.localDataManager.addSignup(raceId, signupData);
    
    if (success) {
      wx.showToast({ title: '报名成功', icon: 'success' });
      
      // 更新比赛信息
      const raceData = this.localDataManager.getRace(raceId);
      if (raceData) {
        raceData.courtCount = this.data.courtCount;
        this.localDataManager.saveRace(raceData);
      }
      
      this.setData({
        showOtherSignupModal: false,
        showSignupAction: false,
        signupIndex: -1,
        tempOtherName: '',
        tempOtherGender: 'male'
      }, () => {
        this.loadSignupList();
      });
    } else {
      wx.showToast({ title: '报名失败', icon: 'none' });
    }
  },
  onCancelOtherSignup() {
    this.setData({
      showOtherSignupModal: false,
      showSignupAction: false,
      signupIndex: -1,
      tempOtherName: '',
      tempOtherGender: 'male'
    });
  },
  onAddGroup() {
    let maxPlayers = this.data.maxPlayers + 2; // 固搭赛一次增加2人
    
    // 更新比赛信息中的maxPlayers
    const raceId = this.options && this.options.id;
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) {
      raceData.maxPlayers = maxPlayers;
      this.localDataManager.saveRace(raceData);
    }
    
    // 重新加载报名列表，让loadSignupList处理更新UI
    this.loadSignupList();
    
    wx.showToast({ title: '增加一组成功', icon: 'success' });
  },
  onRemoveGroup() {
    let maxPlayers = this.data.maxPlayers;
    if (maxPlayers <= 6) {
      wx.showToast({ title: '最少6人', icon: 'none' });
      return;
    }
    maxPlayers -= 2; // 固搭赛一次减少2人
    
    // 获取报名数据
    const raceId = this.options && this.options.id;
    const signupDataList = this.localDataManager.getSignups(raceId) || [];
    
    // 找出order小于新maxPlayers的报名数据并保留
    const filteredSignups = signupDataList.filter(signup => signup.order < maxPlayers);
    
    // 更新本地存储
    this.localDataManager.clearSignups(raceId);
    filteredSignups.forEach(signup => {
      this.localDataManager.addSignup(raceId, signup);
    });
    
    // 更新比赛信息中的maxPlayers
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) {
      raceData.maxPlayers = maxPlayers;
      this.localDataManager.saveRace(raceData);
    }
    
    // 重新加载报名列表，让loadSignupList处理更新UI
    this.loadSignupList();
    
    wx.showToast({ title: '减少一组成功', icon: 'success' });
  },
  reloadRaceInfoAndSignup() {
    const raceId = this.options && this.options.id;
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) {
      this.setData({
        maxPlayers: raceData.maxPlayers || 8,
      }, () => {
        this.loadSignupList();
      });
    }
  },
  onOpenDisclaimer() {
    wx.navigateTo({ url: '/pages/disclaimer/disclaimer' });
  },
  // 公平轮换分组算法，参考多人轮转赛的算法，确保搭档组比赛次数均匀
  generateFairRotation(players, totalMatches, courts) {
    // 在固搭循环赛中，players是个人，但我们需要按搭档组来生成对阵
    const n = players.length;
    const groupCount = Math.floor(n / 2); // 搭档组数量
    
    // 将个人按搭档组重新组织
    const partnerGroups = [];
    for (let i = 0; i < groupCount; i++) {
      const player1 = players[i * 2];
      const player2 = players[i * 2 + 1];
      if (player1 && player2) {
        partnerGroups.push([player1, player2]);
      }
    }
    
    // 记录每个搭档组的比赛次数
    let groupPlayCount = Array(groupCount).fill(0);
    let matchList = [];
    let round = 0;
    
    // 计算每个搭档组应该参赛的次数（理想情况下）
    const totalGroupSlots = totalMatches * 2; // 每场比赛2个搭档组
    const avgMatchesPerGroup = Math.floor(totalGroupSlots / groupCount);
    const extraSlots = totalGroupSlots % groupCount;
    
    // 为每个搭档组分配目标参赛次数
    let targetMatches = Array(groupCount).fill(avgMatchesPerGroup);
    for (let i = 0; i < extraSlots; i++) {
      targetMatches[i]++;
    }
    
    // 生成比赛
    while (matchList.length < totalMatches) {
      // 为每个场地生成比赛
      for (let c = 0; c < courts; c++) {
        if (matchList.length >= totalMatches) break;
        
        // 选择参赛次数最接近目标且最少的搭档组
        let availableGroups = groupPlayCount.map((cnt, idx) => ({
          cnt,
          idx,
          target: targetMatches[idx],
          deficit: targetMatches[idx] - cnt // 还差多少场
        }))
        .filter(g => g.deficit > 0) // 只选择还没达到目标的人
        .sort((a, b) => {
          // 优先选择还差场次最多的搭档组
          if (a.deficit !== b.deficit) return b.deficit - a.deficit;
          // 其次选择当前参赛次数最少的搭档组
          if (a.cnt !== b.cnt) return a.cnt - b.cnt;
          // 最后随机排序
          return Math.random() - 0.5;
        });
        
        // 确保有足够的搭档组
        if (availableGroups.length < 2) {
          // 如果不够2个搭档组，从所有搭档组中选择参赛次数最少的
          availableGroups = groupPlayCount.map((cnt, idx) => ({cnt, idx}))
            .sort((a, b) => a.cnt - b.cnt || Math.random() - 0.5);
        }
        
        // 选择前2个搭档组
        const selectedIndices = availableGroups.slice(0, 2).map(g => g.idx);
        
        // 创建比赛
        const match = {
          left: partnerGroups[selectedIndices[0]],
          right: partnerGroups[selectedIndices[1]],
          status: 'ready',
          round: round + 1,
          courtIndex: c
        };
        
        // 确保比赛有效
        if (match.left && match.right) {
          matchList.push(match);
          
          // 增加参赛次数
          selectedIndices.forEach(idx => {
            if (idx !== undefined && idx < groupCount) {
              groupPlayCount[idx]++;
            }
          });
        }
      }
      round++;
      
      // 防止无限循环
      if (round > totalMatches * 3) break;
    }
    
    return matchList.slice(0, totalMatches);
  },
  onGenerateMatch() {
    if (!this.data.isCreator) {
      wx.showToast({ title: '只有创建人才能生成对阵', icon: 'none' });
      return;
    }
    // 自动推荐局数
    const n = this.data.signupList.filter(item => item).length;
    const c = this.data.courtCount;
    let recommendList = [];
    let minEvenMatch = null;
    // 计算每人同场次的最小局数
    for (let k = 1; k <= 20; k++) { // 限制最大20场，防止死循环
      if ((k * n) % (4 * c) === 0) {
        minEvenMatch = (k * n) / 4;
        break;
      }
    }
    if (minEvenMatch) recommendList.push(minEvenMatch);
    // 其它推荐局数（如每人多打一场、少打一场等）
    for (let delta = 1; delta <= 2; delta++) {
      let k = Math.ceil((minEvenMatch * 4) / n) + delta;
      let total = Math.ceil((k * n) / (4 * c)) * c;
      if (!recommendList.includes(total)) recommendList.push(total);
    }
    this.setData({
      recommendMatchCountList: recommendList,
      matchCount: recommendList[0] || 3 // 默认选第一个推荐值
    });
    if (this.data.showRegenMatchBtn) {
      wx.showModal({
        title: '提示',
        content: '重新生成对阵？现有对局和成绩将全部清除',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.setData({ showMatchModal: true });
          }
        }
      });
    } else {
      this.setData({ showMatchModal: true });
    }
  },
  onConfirmMatchModal() {
    this._doGenerateMatch();
    this.setData({ showMatchModal: false });
  },
  _doGenerateMatch() {
    // 校验报名人数
    if (this.data.signupCount < 6) {
      wx.showToast({
        title: '至少需要6人才能生成对阵',
        icon: 'none'
      });
      return;
    }
    // 校验免责声明
    if (!this.data.disclaimerChecked) {
      wx.showToast({
        title: '请先勾选免责声明',
        icon: 'none'
      });
      return;
    }
    
    // 根据循环次数计算总场数
    const players = this.data.signupList.filter(item => item);
    const playerCount = players.length;
    const groupCount = Math.floor(playerCount / 2); // 搭档组数量
    
    let totalMatches;
    
    switch (this.data.roundType) {
      case 'single':
        // 单循环：每对搭档与其他所有搭档各打一场
        totalMatches = groupCount * (groupCount - 1) / 2;
        break;
      case 'double':
        // 双循环：每对搭档与其他所有搭档各打两场
        totalMatches = groupCount * (groupCount - 1);
        break;
      case 'custom':
        // 自定义：使用用户输入的循环次数
        const customCount = this.data.customRoundCount || 3;
        totalMatches = groupCount * (groupCount - 1) / 2 * customCount;
        break;
      default:
        totalMatches = groupCount * (groupCount - 1) / 2;
    }
    
    const courts = this.data.courtCount;
    const matchList = this.generateFairRotation(players, totalMatches, courts);
    
    // 清空比分和状态
    matchList.forEach(match => {
      match.score = null;
      match.status = 'ready';
    });
    
    const raceId = this.raceId;
    
    // 保存到本地存储
    this.localDataManager.saveMatches(raceId, [{ raceId, matchList }]);
    
    // 更新比赛信息
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) {
      raceData.status = '计分中';
      raceData.matchList = matchList;
      this.localDataManager.saveRace(raceData);
    }
    
    wx.showToast({ title: '对阵已生成' });
    this.loadMatchList();
    this.setData({
      selectedItemIndex: 1
    });
  },
  onCloseMatchModal() {
    this.setData({ showMatchModal: false });
  },
  onStartMatch(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const { filteredMatchList, matchList } = this.data;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在固搭循环赛中，由于可能存在重复的搭档组组合，我们需要使用更精确的匹配方式
    // 不仅要匹配搭档组，还要匹配轮次和场地信息
    const leftNames = target.left.map(p => p.nickName).join(',');
    const rightNames = target.right.map(p => p.nickName).join(',');
    const realIndex = matchList.findIndex(item =>
      item.left.map(p => p.nickName).join(',') === leftNames &&
      item.right.map(p => p.nickName).join(',') === rightNames &&
      item.round === target.round &&
      item.courtIndex === target.courtIndex
    );
    
    if (realIndex === -1) return;
    
    matchList[realIndex].status = 'playing';
    this.setData({ matchList }, () => {
      this.filterMatchList();
    });
  },
  
  onCancelMatch(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const { filteredMatchList, matchList } = this.data;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在固搭循环赛中，由于可能存在重复的搭档组组合，我们需要使用更精确的匹配方式
    // 不仅要匹配搭档组，还要匹配轮次和场地信息
    const leftNames = target.left.map(p => p.nickName).join(',');
    const rightNames = target.right.map(p => p.nickName).join(',');
    const realIndex = matchList.findIndex(item =>
      item.left.map(p => p.nickName).join(',') === leftNames &&
      item.right.map(p => p.nickName).join(',') === rightNames &&
      item.round === target.round &&
      item.courtIndex === target.courtIndex
    );
    
    if (realIndex === -1) return;
    
    matchList[realIndex].status = 'ready';
    this.setData({ matchList }, () => {
      this.filterMatchList();
    });
  },
  onDisclaimerChange(e) {
    this.setData({ disclaimerChecked: e.detail.value.length > 0 });
  },
  onTabChange(e) {
    const idx = Number(e.currentTarget.dataset.index);
    this.setData({ selectedItemIndex: idx });
    
    // 如果切换到成绩标签页，重新计算成绩
    if (idx === 2) {
      this.calculateResults();
    }
  },
  onSelectRoundType(e) {
    const roundType = e.detail.value;
    this.setData({
      roundType: roundType
    });
  },
  onCustomRoundCountInput(e) {
    const value = e.detail.value;
    this.setData({ customRoundCount: parseInt(value) || 0 });
  },
  // 更新搭档组信息
  updatePartnerGroups() {
    const signupList = this.data.signupList || [];
    const partnerGroups = [];
    
    for (let i = 0; i < signupList.length; i += 2) {
      if (i + 1 < signupList.length) {
        partnerGroups.push({
          index: Math.floor(i / 2) + 1,
          player1: signupList[i],
          player2: signupList[i + 1]
        });
      }
    }
    
    this.setData({ partnerGroups });
  },
   updateCourtCountLimit() {
     const n = this.data.signupList.filter(item => item).length;
     let maxCourt = 1;
     if (n >= 16) maxCourt = 4;
     else if (n >= 12) maxCourt = 3;
     else if (n >= 8) maxCourt = 2;
     else maxCourt = 1;
     this.setData({ maxCourtCount: Math.max(1, maxCourt) });
   },
   onCourtRadioGroupChange(e) {
     const newCourtCount = parseInt(e.detail.value);
     this.setData({ courtCount: newCourtCount }, () => {
       // 保存到本地存储
       const raceId = this.options && this.options.id;
       if (raceId) {
         const raceData = this.localDataManager.getRace(raceId);
         if (raceData) {
           raceData.courtCount = newCourtCount;
           this.localDataManager.saveRace(raceData);
         }
       }
     });
   },
  loadSignupList() {
    const raceId = this.options && this.options.id;
    if (!raceId) return;
    
    // 从本地存储中获取比赛信息
    const raceData = this.localDataManager.getRace(raceId);
    
    // 优先使用raceData中保存的maxPlayers值
    let maxPlayers = 8; // 默认值
    if (raceData && raceData.maxPlayers !== undefined) {
      maxPlayers = raceData.maxPlayers;
    }
    
    // 确保maxPlayers在合理范围内
    maxPlayers = Math.max(8, Math.min(maxPlayers, 28));
    
    // 获取报名数据
    const signupDataList = this.localDataManager.getSignups(raceId) || [];
    
    // 创建固定长度的数组，保持位置信息
    let signupList = new Array(maxPlayers).fill(null);
    
    // 将报名数据按order放置到对应位置
    signupDataList.forEach(item => {
      if (typeof item.order === 'number' && item.order >= 0 && item.order < maxPlayers) {
        const signupItem = {
          _id: item._id,
          order: item.order
        };
        // 复制userInfo的所有属性
        if (item.userInfo) {
          Object.assign(signupItem, item.userInfo);
        }
        signupList[item.order] = signupItem;
      }
    });
    
    // 计算实际报名人数
    const actualCount = signupList.filter(item => item !== null).length;
    
    // 更新页面数据
    this.setData({
      signupList,
      signupCount: actualCount,
      appliedCount: actualCount,
      maxPlayers,
      raceTitle: (raceData ? raceData.title : '') || '',
      'raceInfo.totalNum': maxPlayers
    }, () => {
      // 直接更新搭档组信息，不再重复计算报名人数
      this.updatePartnerGroups();
    });
  },
     loadMatchList() {
    const raceId = this.options && this.options.id;
    if (!raceId) return;
    
    const matchData = this.localDataManager.getMatches(raceId);
    
    if (matchData && matchData.length) {
      // 检查数据格式：如果是对象数组且包含 matchList 属性，则取 matchList
      let matchList;
      if (matchData[0] && matchData[0].matchList) {
        matchList = matchData[0].matchList;
      } else {
        // 否则直接使用 matchData
        matchList = matchData;
      }
      
      this.setData({ matchList }, () => {
        this.setMatchProgress();
        this.filterMatchList();
        this.calculateResults(); // 加载比赛后计算成绩
        
        // 检查是否所有比赛都已完成，如果是则切换到成绩页面
        const allFinished = matchList.every(match => match.status === 'finished');
        if (allFinished && matchList.length > 0) {
          this.setData({ selectedItemIndex: 2 });
        }
      });
    }
  },
   setMatchProgress() {
     const matchList = this.data.matchList || [];
     const finishedCount = matchList.filter(item => item.status === 'finished').length;
     this.setData({ finishedCount });
   },
     filterMatchList() {
    const { matchList, scoreTabIndex } = this.data;
    
    // 确保 matchList 是数组
    if (!Array.isArray(matchList)) {
      this.setData({ 
        filteredMatchList: [], 
        scoreTabList: [
          { title: '全部', count: 0 },
          { title: '未结束', count: 0 },
          { title: '可以比赛', count: 0 },
          { title: '比赛中', count: 0 }
        ] 
      });
      return;
    }
    
    let filtered = [];
    if (scoreTabIndex === 0) {
      filtered = matchList;
    } else if (scoreTabIndex === 1) {
      filtered = matchList.filter(item => item.status === 'ready' || item.status === 'playing');
    } else if (scoreTabIndex === 2) {
      filtered = matchList.filter(item => item.status === 'ready');
    } else if (scoreTabIndex === 3) {
      filtered = matchList.filter(item => item.status === 'playing');
    }
    
    const tabList = [
      { title: '全部', count: matchList.length },
      { title: '未结束', count: matchList.filter(item => item.status === 'ready' || item.status === 'playing').length },
      { title: '可以比赛', count: matchList.filter(item => item.status === 'ready').length },
      { title: '比赛中', count: matchList.filter(item => item.status === 'playing').length }
    ];
    this.setData({ filteredMatchList: filtered, scoreTabList: tabList });
  },
   onQuickSignup() {
     this.setData({ showQuickSignupModal: true, quickSignupText: '' });
   },
   onCloseQuickSignup() {
     this.setData({ showQuickSignupModal: false, quickSignupText: '' });
   },
   onQuickSignupInput(e) {
     this.setData({ quickSignupText: e.detail.value });
   },
   onConfirmQuickSignup() {
     const text = this.data.quickSignupText || '';
     // 逐行匹配，兼容多种点号和行首空格、全角空格、点号后空格
     const lines = text.split('\n').map(line => line.replace(/^\s+|\s+$/g, ''));
     const filterKeywords = ['场', '封车', '锁死', '钥匙'];
     // 允许点号后有任意空格，且点号可为.、．、。 、
     const partnerGroups = lines
       .filter(line => /^[\s\u3000]*\d+[\.．。、]\s*[^\s]+/.test(line))
       .map(line => line.replace(/^[\s\u3000]*\d+[\.．。、]\s*/, ''))
       .filter(name => !filterKeywords.some(keyword => name.includes(keyword)));
     if (!partnerGroups.length) {
       wx.showToast({ title: '请粘贴有效的接龙内容', icon: 'none' });
       return;
     }
     
     // 解析搭档组合，支持空格或+分割
     const signupList = [];
     let order = 0;
     console.log('解析到的partnerGroups:', partnerGroups);
     console.log('partnerGroups长度:', partnerGroups.length);
     
     for (const partnerGroup of partnerGroups) {
       // 使用空格或+分割两个搭档
       const partners = partnerGroup.split(/[\s+]/).filter(partner => partner.trim());
       
       if (partners.length >= 2) {
         // 添加第一个搭档
         signupList.push({
           nickName: partners[0].trim(),
           avatarUrl: '../../images/avatar_boy.png',
           gender: 'male',
           order: order++
         });
         
         // 添加第二个搭档
         signupList.push({
           nickName: partners[1].trim(),
           avatarUrl: '../../images/avatar_boy.png',
           gender: 'male',
           order: order++
         });
       } else if (partners.length === 1) {
         // 只有一个名字的情况，可能是单个报名
         signupList.push({
           nickName: partners[0].trim(),
           avatarUrl: '../../images/avatar_boy.png',
           gender: 'male',
           order: order++
         });
       }
     }
     
     const raceId = this.options && this.options.id;
     wx.showModal({
       title: '提示',
       content: '导入报名会清空原来的报名信息，是否导入？',
       confirmText: '导入',
       cancelText: '取消',
       success: (res) => {
         if (res.confirm) {
           // 彻底清空报名，等待清空完成后再导入
           setTimeout(async () => { await this.importSignupBatch(signupList, raceId); }, 100);
         }
       }
     });
   },
   onQuickSignupBtn() {
     this.setData({ showQuickSignupModal: true });
   },
   async importSignupBatch(signupList, raceId) {

     // 检查最大人数限制
     const maxPlayers = 28;
     let processedSignupList = signupList;
     let showMessage = '已导入报名';
     
     if (signupList.length > maxPlayers) {
       // 截取前maxPlayers人
       processedSignupList = signupList.slice(0, maxPlayers);
       showMessage = '已导入(限28人)';
     }
     
     // 清空现有报名
     this.localDataManager.clearSignups(raceId);
     
     // 批量添加到本地存储
     for (const item of processedSignupList) {
       const signupData = {
         raceId,
         order: item.order,
         userInfo: {
           nickName: item.nickName,
           avatarUrl: item.avatarUrl,
           gender: item.gender
         }
       };
       this.localDataManager.addSignup(raceId, signupData);
     }
     
     wx.showToast({ title: showMessage, icon: 'success' });
     this.setData({ showQuickSignupModal: false, quickSignupText: '' });
     
     // 导入后调试输出报名顺序
     const signupDataList = this.localDataManager.getSignups(raceId);
     const debugList = (signupDataList || []).map(item => ({ order: item.order, nickName: item.userInfo.nickName }));
     console.log('导入后的报名数据:', debugList);
     console.log('导入的数据总数:', debugList.length);
     console.log('原始解析的signupList长度:', signupList.length);
      
     // 明确设置maxPlayers为28，确保能够显示所有导入的人
     const raceData = this.localDataManager.getRace(raceId);
     if (raceData) {
       raceData.maxPlayers = 28;
       this.localDataManager.saveRace(raceData);
     }

     this.loadSignupList();
   },
   onEditSignup(e) {
     const index = e.currentTarget.dataset.index;
     const { signupList } = this.data;
     const item = signupList[index];
     if (!item || !item.nickName) return;
     wx.showModal({
       title: '编辑报名昵称',
       editable: true,
       placeholderText: '请输入新昵称',
       content: item.nickName,
       success: (res) => {
         if (res.confirm && res.content && res.content !== item.nickName) {
           // 更新本地存储
           const raceId = this.options && this.options.id;
           const signupDataList = this.localDataManager.getSignups(raceId);
           const targetSignup = signupDataList.find(signup => 
             signup.userInfo.nickName === item.nickName && signup.order === item.order
           );
           
           if (targetSignup) {
             targetSignup.userInfo.nickName = res.content;
             this.localDataManager.updateSignup(raceId, targetSignup);
             wx.showToast({ title: '已修改' });
             this.loadSignupList();
           } else {
             wx.showToast({ title: '修改失败', icon: 'none' });
           }
         }
       }
     });
   },
  // 编辑报名弹窗输入
  onEditSignupNameInput(e) {
    // 实时更新 editSignupName，确保输入框和数据同步
    this.setData({ editSignupName: e.detail.value });
  },
  onEditSignupGenderSelect(e) {
    this.setData({ editSignupGender: e.currentTarget.dataset.gender });
  },
  onConfirmEditSignup() {
    const { editSignupIndex, editSignupName, editSignupGender, signupList } = this.data;
    const item = signupList[editSignupIndex];
    if (!item || !editSignupName.trim() || !item._id) {
      wx.showToast({ title: '数据异常', icon: 'none' });
      return;
    }
    // 根据性别切换默认头像
    let avatarUrl = item.avatarUrl;
    if (editSignupGender === 'female') {
      avatarUrl = '../../images/avatar_girl.png';
    } else if (editSignupGender === 'male') {
      avatarUrl = '../../images/avatar_boy.png';
    }
    // 更新本地存储中的报名信息
    const raceId = this.options && this.options.id;
    const signupDataList = this.localDataManager.getSignups(raceId);
    const targetSignup = signupDataList.find(signup => signup._id === item._id);
    
    if (targetSignup) {
      targetSignup.userInfo.nickName = editSignupName;
      targetSignup.userInfo.gender = editSignupGender;
      targetSignup.userInfo.avatarUrl = avatarUrl;
      this.localDataManager.updateSignup(raceId, targetSignup);
      
      console.log('更新成功');
      wx.showToast({ title: '已修改' });
      this.setData({ showEditSignupModal: false }, () => {
        this.loadSignupList();
      });
    } else {
      wx.showToast({ title: '修改失败', icon: 'none' });
      console.error('报名信息修改失败：未找到对应记录');
    }
  },
  onCancelEditSignup() {
    this.setData({ showEditSignupModal: false });
  },
  onBack() {
    // 返回到比赛列表页
    wx.navigateBack({
      fail: () => {
        // 如果返回失败，则跳转到列表页
        wx.switchTab({ url: '/pages/list/list' });
      }
    });
  },
  
  // 计分相关方法
  onOpenScoreModal(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const { filteredMatchList, matchList } = this.data;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在固搭循环赛中，由于可能存在重复的搭档组组合，我们需要使用更精确的匹配方式
    // 不仅要匹配搭档组，还要匹配轮次和场地信息
    const leftNames = target.left.map(p => p.nickName).join(',');
    const rightNames = target.right.map(p => p.nickName).join(',');
    const realIndex = matchList.findIndex(item =>
      item.left.map(p => p.nickName).join(',') === leftNames &&
      item.right.map(p => p.nickName).join(',') === rightNames &&
      item.round === target.round &&
      item.courtIndex === target.courtIndex
    );
    
    if (realIndex === -1) return;
    
    const match = matchList[realIndex];
    
    this.setData({
      scoreModalVisible: true,
      scoreModalIndex: realIndex,
      scoreLeft: match.score ? match.score.left : '',
      scoreRight: match.score ? match.score.right : '',
      scoreModalLeft: match.left || [],
      scoreModalRight: match.right || []
    });
  },
  
  onScoreInput(e) {
    const { side } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    // 只允许输入数字
    if (value && !/^\d*$/.test(value)) {
      wx.showToast({ title: '只能输入数字', icon: 'none' });
      return;
    }
    
    this.setData({ [side]: value });
  },
  
  onConfirmScoreModal() {
    const { scoreModalIndex, scoreLeft, scoreRight, matchList } = this.data;
    
    if (!scoreLeft || !scoreRight) {
      wx.showToast({ title: '请输入完整比分', icon: 'none' });
      return;
    }
    
    // 校验输入为数字
    if (isNaN(Number(scoreLeft)) || isNaN(Number(scoreRight))) {
      wx.showToast({ title: '比分只能输入数字', icon: 'none' });
      return;
    }
    
    if (scoreModalIndex === -1 || !matchList[scoreModalIndex]) {
      wx.showToast({ title: '比赛数据异常', icon: 'none' });
      return;
    }
    
    // 直接更新比赛数据（与多人轮转赛保持一致）
    matchList[scoreModalIndex].score = { left: Number(scoreLeft), right: Number(scoreRight) };
    matchList[scoreModalIndex].status = 'finished';
    
    // 检查是否所有比赛都已完成
    const allFinished = matchList.every(match => match.status === 'finished');
    if (allFinished) {
      // 如果所有比赛都完成，更新比赛状态为"已完赛"
      const raceData = this.localDataManager.getRace(this.raceId);
      if (raceData) {
        raceData.status = '已完赛';
        this.localDataManager.saveRace(raceData);
      }
      
      // 自动切换到成绩页面
      this.setData({ selectedItemIndex: 2 }, () => {
        // 滚动到页面顶部
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        });
      });
      wx.showToast({ title: '所有比赛已完成，已切换到成绩页面', icon: 'success' });
    } else {
      wx.showToast({ title: '比分已保存', icon: 'success' });
    }
    
    // 与多人轮转赛保持一致：在setData中同时重置scoreModalIndex
    this.setData({
      matchList,
      scoreModalVisible: false,
      scoreModalIndex: -1,
      scoreLeft: '',
      scoreRight: ''
    }, () => {
      this.setMatchProgress();
      this.filterMatchList();
      this.calculateResults(); // 计算成绩
    });
    
    // 保存到本地存储（在setData之后，与多人轮转赛保持一致）
    const raceId = this.raceId;
    this.localDataManager.saveMatches(raceId, [{ raceId, matchList }]);
  },
  
  // 计算成绩排名
  calculateResults() {
    const { matchList } = this.data;
    const finishedMatches = matchList.filter(match => match.status === 'finished' && match.score);
    
    if (finishedMatches.length === 0) {
      this.setData({ resultList: [] });
      return;
    }
    
    // 统计搭档组成绩
    const comboMap = {};
    
    finishedMatches.forEach(match => {
      const leftKey = match.left.map(p => p.nickName).join('+');
      const rightKey = match.right.map(p => p.nickName).join('+');
      
      if (!comboMap[leftKey]) {
        comboMap[leftKey] = { 
          combo: match.left.slice(), 
          win: 0, 
          lose: 0,
          score: 0,
          players: match.left.map(p => p.nickName).join('+')
        };
      }
      if (!comboMap[rightKey]) {
        comboMap[rightKey] = { 
          combo: match.right.slice(), 
          win: 0, 
          lose: 0,
          score: 0,
          players: match.right.map(p => p.nickName).join('+')
        };
      }
      
      if (match.score.left > match.score.right) {
        comboMap[leftKey].win += 1;
        comboMap[leftKey].score += match.score.left - match.score.right;
        comboMap[rightKey].lose += 1;
        comboMap[rightKey].score -= match.score.left - match.score.right;
      } else {
        comboMap[rightKey].win += 1;
        comboMap[rightKey].score += match.score.right - match.score.left;
        comboMap[leftKey].lose += 1;
        comboMap[leftKey].score -= match.score.right - match.score.left;
      }
    });
    
    // 生成成绩数组
    const resultList = Object.values(comboMap).map((item, idx) => {
      const resultItem = {};
      // 复制item的所有属性
      for (let key in item) {
        if (item.hasOwnProperty(key)) {
          resultItem[key] = item[key];
        }
      }
      resultItem.idx = idx;
      return resultItem;
    });
    
    // 排序：先按胜局，再按净胜分降序
    resultList.sort((a, b) => b.win - a.win || b.score - a.score);
    
    this.setData({ resultList });
  },
  
  onCloseScoreModal() {
    this.setData({
      scoreModalVisible: false,
      scoreModalIndex: -1,
      scoreLeft: '',
      scoreRight: '',
      scoreModalLeft: [],
      scoreModalRight: []
    });
  },

  // 刷新比赛数据
  onScoreRefresh() {
    this.loadMatchList();
    this.filterMatchList();
    wx.showToast({ title: '已刷新', icon: 'success' });
  },

  // 切换计分标签页
  onScoreTabChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      scoreTabIndex: index
    });
    this.filterMatchList();
  }
});